<template>
  <div class="main-content pd16">

    <!--搜索栏-->
    <el-form class="search-form" ref="searchFormRef" :model="searchForm" :inline="true" label-width="70">

      <el-form-item label="字典名称" prop="dictName" label-width="70">
        <el-input v-model="searchForm.dictName" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item label="字典KEY" prop="dictKey" label-width="70">
        <el-input v-model="searchForm.dictKey" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item label="字典值" prop="dictValue" label-width="70">
        <el-input v-model="searchForm.dictValue" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item label="模块名称" prop="moduleName" label-width="70">
        <el-input v-model="searchForm.moduleName" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item label="状态" prop="status" label-width="40">
        <el-select v-model="searchForm.status" placeholder="请选择" clearable style="width: 100px">
          <el-option v-for="dict in enu_common_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="类型" prop="type" label-width="40">
        <el-select v-model="searchForm.type" placeholder="请选择" clearable style="width: 100px">
          <el-option v-for="dict in enu_sys_dict_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="searchData">搜索</el-button>
        <el-button icon="Refresh" @click="resetSearch">重置</el-button>
      </el-form-item>

    </el-form>

    <!--按钮组-->
    <div class="fx mgb12">
      <el-button type="primary" plain size="small" icon="Plus" @click="openAdd">新增字典</el-button>
      <el-button type="danger" plain size="small" icon="Delete" @click="deleteBatch">批量删除</el-button>
      <el-button type="warning" plain size="small" icon="Delete" @click="refreshCache">更新缓存</el-button>
    </div>

    <!--表格-->
    <el-table border highlight-current-row row-key="id"
              v-loading="option.loading" :data="option.tableData"
              @selection-change="selectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="ID" prop="id" :show-overflow-tooltip="true" width="100">
        <template #default="scope">
          <span @click="clipboard(scope.row.id,'已复制到剪切板')"> {{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模块名称" prop="moduleName" :show-overflow-tooltip="true" width="90">
        <template #default="scope">
          <span style="font-size: 16px"> {{ scope.row.moduleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="字典名称" prop="dictName" :show-overflow-tooltip="true" width="170"></el-table-column>

      <el-table-column label="字典KEY" prop="dictKey" :show-overflow-tooltip="true" width="300"></el-table-column>

      <el-table-column label="字典值" prop="dictValue" :show-overflow-tooltip="true" width="300"></el-table-column>

      <el-table-column label="类型" align="center" prop="type" :show-overflow-tooltip="true" width="120">
        <template #default="scope">
          <dict-tag :options="enu_sys_dict_type" :value="scope.row.type"></dict-tag>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status" :show-overflow-tooltip="true" width="80">
        <template #default="scope">
          <dict-tag :options="enu_common_status" :value="scope.row.status"></dict-tag>
        </template>
      </el-table-column>

      <el-table-column label="排序" prop="sort"
                       :show-overflow-tooltip="true" width="80"></el-table-column>

      <el-table-column label="创建时间" align="center" prop="ct" width="170"></el-table-column>

      <el-table-column label="操作" align="center" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="openEdit(scope.row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div class="fx_end">
      <el-pagination class="mgt8" small background :total="option.totalRow" :page-sizes="option.pageSizes"
                     v-model:current-page="searchForm.pageNumber" v-model:page-size="searchForm.pageSize"
                     layout="total, sizes, prev, pager, next, jumper" @size-change="searchData"
                     @current-change="searchData"/>
    </div>

    <!--Dialog-->
    <el-dialog :title="option.dialogTitle" v-model="option.openDialog" width="680" :close-on-click-modal="false"
               draggable append-to-body destroy-on-close>

      <el-form ref="formDataRef" size="default" :model="formData" :rules="formRules" label-width="100">

        <el-form-item label="模块名称" prop="moduleName">
          <el-input v-model="formData.moduleName" placeholder="请输入" style="width: 500px"/>
        </el-form-item>

        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="formData.dictName" placeholder="请输入" style="width: 500px"/>
        </el-form-item>

        <el-form-item label="字典KEY" prop="dictKey">
          <el-input v-model="formData.dictKey" placeholder="请输入" style="width: 500px"/>
        </el-form-item>

        <el-form-item label="字典值" prop="dictValue">
          <el-input v-model="formData.dictValue" placeholder="请输入" style="width: 500px"/>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" controls-position="right" :min="0" style="width: 500px"/>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" maxlength="500" placeholder="请输入" show-word-limit
                    :autosize="{ minRows: 2, maxRows: 6 }"
                    style="width: 500px" type="textarea"/>
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button @click="()=>{option.openDialog=false}">取 消</el-button>
        <el-button v-if="option.dialogType==='add'" type="primary" @click="submitAdd">确 定</el-button>
        <el-button v-if="option.dialogType==='edit'" type="primary" @click="submitEdit">保 存</el-button>
      </template>

    </el-dialog>


  </div>
</template>

<script setup>
import {getCurrentInstance, onMounted, ref} from "vue";
import {apiAllMyCreateRole, apiDictClearCache, apiDictDelete, apiDictInsert, apiDictPage, apiDictUpdate} from "@/api/system";
import $modal from "@/common/utils/modal";
import {blankStr, clipboard, copyNew} from "@/common/utils/kit";
import {asDict} from "@/api/common";
import DictTag from "@/common/component/DictTag.vue";

const {enu_common_status, enu_sys_dict_type} = asDict("enu_common_status", "enu_sys_dict_type");

const {proxy} = getCurrentInstance();

const optionKey = {
  loading: false,
  dialogType: "",
  dialogTitle: "",
  openDialog: false,
  tableData: [],
  selectIds: [],
  selectNames: [],
  pageSizes: [1, 10, 20, 50, 100],
  totalRow: 0,
  nowRoleId: 0,
  defaultChecked: [],
  allRole: [],
}

const formKey = {
  id: "",
  sort: 100,
  remark: "",
  moduleName: "",
  dictName: "",
  dictValue: "",
  dictKey: "",
}

const searchKey = {
  id: "",
  sort: 100,
  remark: "",
  moduleName: "",
  dictName: "",
  dictValue: "",
  dictKey: "",
}

const formRules = ref({
  dictName: [{required: true, message: "不能为空", trigger: "blur"}],
  dictValue: [{required: true, message: "不能为空", trigger: "blur"}],
  dictKey: [{required: true, message: "不能为空", trigger: "blur"}],
});
const searchForm = ref(searchKey)
const formData = ref(formKey);
const option = ref(optionKey);

function resetForm() {
  formData.value = copyNew(formKey)
}

function resetSearch() {
  proxy.$refs["searchFormRef"].resetFields();
}

//页面加载完成回调
onMounted(() => {

  searchData()

  apiAllMyCreateRole().then(res => {
    option.value.allRole = res.data
  })

})

function selectionChange(rows) {
  option.value.selectIds = rows.map(item => item.id);
  option.value.selectNames = rows.map(item => blankStr(item.moduleName, "") + "-" + blankStr(item.dictName, ""));
}

//搜索数据
function searchData() {
  option.value.loading = true;
  apiDictPage(searchForm.value).then(res => {
    let {totalRow, records, pageNumber, pageSize} = res.data;
    option.value.loading = false;
    option.value.totalRow = totalRow * 1
    option.value.tableData = records
    searchForm.value.pageNumber = pageNumber * 1
    searchForm.value.pageSize = pageSize * 1
  })
}

function openAdd() {
  resetForm()
  option.value.dialogTitle = "新增字典";
  option.value.openDialog = true;
  option.value.dialogType = "add";
}

function openEdit(row) {
  //console.log(row)
  option.value.dialogTitle = "编辑字典信息";
  option.value.openDialog = true;
  option.value.dialogType = "edit";
  formData.value = copyNew(row);
  formData.value.roleIds = formData.value.roleIds ? formData.value.roleIds.split(",") : []
}

function submitAdd() {
  proxy.$refs["formDataRef"].validate(valid => {

    if (valid) {
      apiDictInsert(formData.value).then(res => {
        if (res.success) {
          //console.log(res)
          $modal.success();
          option.value.openDialog = false;
          searchData()
        }
      })
    }

  });
}

function submitEdit() {
  proxy.$refs["formDataRef"].validate(valid => {

    if (valid) {
      apiDictUpdate(formData.value).then(res => {
        if (res.success) {
          //console.log(res)
          $modal.success();
          option.value.openDialog = false;
          searchData()
        }
      })
    }

  });
}

function refreshCache() {
  //console.log(ids)
  let content = `是否更新全部缓存？`
  $modal.confirmWarning(content)
      .then(async () => {
        apiDictClearCache().then((res) => {
          if (res.success) {
            $modal.success();
            searchData()
          }
        });
      }).catch(() => $modal.cancel());
}

function deleteBatch() {
  if (option.value.selectIds.length === 0) {
    $modal.warning("请至少选择一条数据");
    return;
  }

  //console.log(ids)
  let content = `正在删除名称为【 ${option.value.selectNames.join("、")}】 的数据项，是否确定删除？ `
  $modal.confirmWarning(content)
      .then(async () => {
        let res = await apiDictDelete({ids: option.value.selectIds.join(",")})
        if (res.success) {
          $modal.success();
          searchData()
        }
      }).catch(() => $modal.cancel());
}

</script>

<style scoped lang="less">

</style>